package com.group4.datafactorybackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group4.datafactorybackend.common.R;
import com.group4.datafactorybackend.common.enums.ResultCodeEnum;
import com.group4.datafactorybackend.entity.DO.MenuDO;
import com.group4.datafactorybackend.entity.VO.MenuVO;
import com.group4.datafactorybackend.mapper.MenuMapper;
import com.group4.datafactorybackend.service.MenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 卑微小峰
 * @date 2022/8/15
 * @description 菜单管理业务逻辑实现层
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuDO> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    /**
     * @author 卑微小峰
     * @return R
     * @description 获取菜单列表
     */
    @Override
    public R<?> listMenu() {
        LambdaQueryWrapper<MenuDO> listMenuWrapper = new LambdaQueryWrapper<>();
        // 查询所有顶级菜单
        listMenuWrapper.isNull(MenuDO::getParentCode);
        List<MenuDO> baseMenuList = menuMapper.selectList(listMenuWrapper);
        List<MenuVO> menuList = new ArrayList<>();
        for (MenuDO m : baseMenuList) {
            MenuVO menu = new MenuVO();
            BeanUtils.copyProperties(m, menu);
            menu.setChildren(listChildMenu(menu.getMenuCode()));
            menuList.add(menu);
        }
        return R.Success(ResultCodeEnum.SUCCESS, menuList);
    }

    /**
     * @author 卑微小峰
     * @param parentCode 父级编号
     * @return List
     * @description 递归获取菜单层级列表
     */
    public List<MenuVO> listChildMenu(Long parentCode) {
        // 查询当前父级编号下的所有子菜单
        List<MenuVO> menuVOList = new ArrayList<>();
        LambdaQueryWrapper<MenuDO> menuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        menuLambdaQueryWrapper.eq(MenuDO::getParentCode, parentCode);
        List<MenuDO> menuDOList = menuMapper.selectList(menuLambdaQueryWrapper);
        for (MenuDO menuDO : menuDOList) {
            MenuVO menuVO = new MenuVO();
            BeanUtils.copyProperties(menuDO, menuVO);
            menuVOList.add(menuVO);
        }
        // 如果集合长度大于0，表示存在下级目录，遍历集合查询下级目录,否则直接返回数据
        if (menuVOList.size() > 0) {
            for (MenuVO menuVO : menuVOList) {
                //再通过其id作为pid查询他的下级目录
                menuVO.setChildren(listChildMenu(menuVO.getMenuCode()));
            }
        }
        return menuVOList;
    }
}
